package com.java1234.util;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 数据库工具类
 * 
 * @author 15375
 *
 */
public class DbUtil {
	private String dbUrl = "jdbc:mysql://localhost:3306/db_book?" + PARAMETER8;// 数据库连接地址
	private String dbUserName = "root";// 用户名
	private String dbPassword = "123456";// 密码
	private static final String PARAMETER8 = "characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8"; // Mysql8以上版本连接参数需设置时区
	private String jdbcName = "com.mysql.cj.jdbc.Driver";// 驱动名称
	private static Connection con;

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 * @throws Exception
	 */
	public Connection getCon() throws Exception {
		Class.forName(jdbcName);
		Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);
		return con;
	}

	/**
	 * 关闭数据库连接
	 * 
	 * @param con
	 * @throws Exception
	 */
	public void closeCon(Connection con) throws Exception {
		if (con != null) {
			con.close();
		}
	}

	public static void main(String[] args) {
		DbUtil dbUtil = new DbUtil();
		try {
			dbUtil.getCon();
			System.out.println("数据库连接成功！");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("数据库连接失败！");
		}

	}

	public void close(PreparedStatement ps, ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (ps != null) {
				ps.close();
				ps = null;
			}
			if (con != null) {
				con.close();
				con = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
